package br.net.woodstock.tickettoride.client.utils;

import java.nio.charset.Charset;
import java.security.Key;

import br.net.woodstock.rockframework.security.crypt.impl.CrypterOperation;
import br.net.woodstock.rockframework.security.crypt.impl.CrypterOperation.Mode;
import br.net.woodstock.rockframework.security.digest.DigestType;
import br.net.woodstock.rockframework.security.digest.Digester;
import br.net.woodstock.rockframework.security.digest.impl.AsStringDigester;
import br.net.woodstock.rockframework.security.digest.impl.BasicDigester;
import br.net.woodstock.rockframework.security.digest.impl.HexDigester;
import br.net.woodstock.rockframework.utils.Base64Utils;
import br.net.woodstock.rockframework.utils.HexUtils;

public abstract class CodecUtils {

	public static final Charset		CHARSET			= Charset.defaultCharset();

	private static final Digester	SHA1_DIGESTER	= new AsStringDigester(new HexDigester(new BasicDigester(DigestType.SHA1)));

	private static final Digester	MD5_DIGESTER	= new AsStringDigester(new HexDigester(new BasicDigester(DigestType.MD5)));

	public static byte[] toBase64(final byte[] data) {
		return Base64Utils.toBase64(data);
	}

	public static String toBase64String(final byte[] data) {
		return new String(Base64Utils.toBase64(data), CodecUtils.CHARSET);
	}

	public static byte[] fromBase64(final byte[] data) {
		return Base64Utils.fromBase64(data);
	}

	public static byte[] toHex(final byte[] data) {
		return HexUtils.toHex(data);
	}

	public static String toHexString(final byte[] data) {
		return new String(HexUtils.toHex(data), CodecUtils.CHARSET);
	}

	public static byte[] getSHA1(final byte[] data) {
		return CodecUtils.SHA1_DIGESTER.digest(data);
	}

	public static String getSHA1String(final byte[] data) {
		return new String(CodecUtils.SHA1_DIGESTER.digest(data));
	}

	public static byte[] getMD5(final byte[] data) {
		return CodecUtils.MD5_DIGESTER.digest(data);
	}

	public static String getMD5String(final byte[] data) {
		return new String(CodecUtils.MD5_DIGESTER.digest(data));
	}

	public static byte[] encrypt(final Key key, final byte[] data) {
		CrypterOperation operation = new CrypterOperation(key, Mode.ENCRYPT, data);
		return operation.execute();
	}

	public static byte[] decrypt(final Key key, final byte[] data) {
		CrypterOperation operation = new CrypterOperation(key, Mode.DECRYPT, data);
		return operation.execute();
	}
}
